#conftest.py这个文件名称是固定的，主要作用是，可以重写pytest自带的一些钩子函数，或者统一管理一些自定义的fixture函数
import pytest

from api.basic_api import BaseBuyerApi, BaseSellerApi, BaseManagerApi
from api.buyer.login_api import BuyerLoginApi
from api.buyer.member_address_api import SelectMemberAddressListApi, DeleteMemberAddressApi
from api.manager.goods import BatchAuditGoodsApi
from api.manager.login import ManagerLoginApi
from api.seller.goods_api import AddGoodsApi, UnderGoodsApi, RecycleGoodsApi, DeleteGoodsApi, \
    GetGoodsSkuInfoApi
from api.seller.login_api import SellerLoginApi
from common.db_util import DBUtil
from common.file_load import load_yaml_file
from common.json_util import extract_json
from common.logger import GetLogger
from common.redis_util import RedisUtil
from testcases.buyer.test_003_member_address import TestMemberAddress


def pytest_collection_modifyitems(items):
    """
    测试用例收集完成时，将收集到的item的name和nodeid的中文显示在控制台上
    :return:
    """
    for item in items:
        item.name = item.name.encode("utf-8").decode("unicode_escape")
        item._nodeid = item.nodeid.encode("utf-8").decode("unicode_escape")



# def pytest_collection_modifyitems(
#         session:"Session",config:"Config",items:List["Item"]
# ) -> None:
#     #item表示每个测试用例，解决用例名称中文显示问题
#     for item in items:
#         for item in items:
#             item.name = item.name.encode("utf-8").decode("unicode_escape")
#             item._nodeid = item.nodeid.encode("utf-8").decode("unicode_escape")


#通过@pytest.fixture()修饰的函数就是自定义的fixture
#scope参数表示该fixture函数的作用范围
#function 表示在该fixture在每个擦拭函数执行就会执行
#class 表示该fixture函数在每个测试类执行时执行
#moudle 表示该fixture在每个测试模块执行都会执行
#package 表示该fixture的测试包执行性
#session 表示运行一次执行一次

#autouse 该参数表示这个fixture函数，True表示自动执行，Flase则不会自动执行，需要调用执行
@pytest.fixture(scope="session",autouse = True)
def buyer_login(worker_id):#注意这个worker_id指的是当前进程id,由pytest-xdist提供
    #worker_id就是gw0,gw1,gw2

    common_info = load_yaml_file('/config/common.yml')
    # username_list = common_info["buyerName"]
    # password_list= common_info["buyerPassword"]
    # if worker_id == 'master':
    #     username=username_list[0]
    #     password=password_list[0]
    # else:
    #     index = int(worker_id[2:])
    #     username=username_list[index]
    #     password=password_list[index]
    resp = BuyerLoginApi(username=common_info["buyerName"],password=common_info["buyerPassword"]).send()
    BaseBuyerApi.buyer_token = resp.json()['access_token']
    BaseBuyerApi.buyer_uid=resp.json()['uid']
    # yield  BuyerLoginApi.buyer_token#通过yield来区分前置和后置
@pytest.fixture(scope="session",autouse = True)
def seller_login():
    common_info = load_yaml_file('/config/common.yml')
    resp = SellerLoginApi(username=common_info['sellerName'],password=common_info['sellerPassword']).send()
    BaseSellerApi.seller_token = resp.json()['access_token']
@pytest.fixture(scope="session",autouse = True)
def manager_login():
    common_info = load_yaml_file('/config/common.yml')
    resp = ManagerLoginApi(username=common_info['managerName'],password=common_info['managerPassword']).send()
    BaseManagerApi.manager_token= resp.json()['access_token']
@pytest.fixture(scope="session",autouse = True)
def alogger():
    GetLogger.get_logger()
@pytest.fixture(scope="function",autouse = True)
def get_db():
    db_info = load_yaml_file('/config/db.yml')['mtxshop']

    db_util = DBUtil(host=db_info['host'],
                     user=db_info['username'],
                     password=db_info['password'], )
    yield db_util
    db_util.close()
@pytest.fixture(scope="function",autouse = True)
def get_redis():
    redis_info = load_yaml_file('/config/redis.yml')['mtxshop']
    redis_util = RedisUtil(host=redis_info['host'], password=redis_info['password'])
    yield redis_util
# 产品数据准备及清除
@pytest.fixture(scope='class',autouse=False)
def goods_data():
    # 卖家发布商品-->管理员审核产品
    resp = AddGoodsApi().send() # 卖家发布商品
    # 得到发布成功的商品id
    goods_id = extract_json(resp.json(),"$.goods_id")
    # 管理员审核商品
    BatchAuditGoodsApi(goods_ids=[goods_id]).send()
    # 审核通过后，需要想办法得到商品对应的sku_id
    # 使用接口来获取该商品对应的sku_id
    resp = GetGoodsSkuInfoApi(goods_id=goods_id).send()
    # 从响应中得到sku_id的值
    sku_id = extract_json(resp.json(),'$.[0].sku_id')
    yield sku_id,goods_id # 返回sku_id,goods_id
    # 从这里之后就后置处理，用来清除数据
    # 卖家下架商品 -->卖家删除商品(回收站) -->卖家彻底删除商品
    UnderGoodsApi(goods_ids=[goods_id]).send() # 下架商品
    RecycleGoodsApi(goods_ids=[goods_id]).send()# 卖家删除商品(回收站)
    DeleteGoodsApi(goods_ids=[goods_id]).send() # 卖家彻底删除商品

#封装一个fixture,主要完成会员低至的判断，如果满了20个，删除其中一个
@pytest.fixture(scope='class',autouse=False)
def address_data():
    resp=SelectMemberAddressListApi().send()
    address_list=resp.json()
    if len(address_list)==20:
#删除其中一个，默认地址无法删除
        extract_json(address_list,'$.[?(@.def_addr==0)].add_id')
        DeleteMemberAddressApi(address_id=TestMemberAddress.address_id).send()
    else:
        pass

